package com.menu.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.menu.Mapper.GoodsMapper;
import com.menu.Pojo.Goods;
import com.menu.Service.GoodsService;
import com.menu.Utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMappper;
    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addGoods(Goods goods, MultipartFile multipartFile) {
        Integer i = goodsMappper.add(goods);
        if (i == null){
            return ResponseResult.error("添加失败，服务器繁忙！");
        }
        ResponseResult responseResult = fileUtils.uploadGoods(multipartFile,goods.getGoodsId());
        if (responseResult.getCode() == 200){
            Object object = responseResult.getObject();
            String fileName = (String) object;
            goods.setGoodsSurfaceimg(fileName);
            if (goodsMappper.updateImg(goods.getGoodsId(),fileName) == 1){
                return ResponseResult.success("添加成功！");
            }else{
                fileUtils.deleteFile(fileName);
            }
        }
        return responseResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult modifyGoods(Goods goods, MultipartFile multipartFile) {
        Integer i = goodsMappper.modifyGoods(goods);
        if (i == null || i == 0){
            return ResponseResult.error("更新失败，服务器繁忙！");
        }
        ResponseResult responseResult = null;
        if(multipartFile != null && !multipartFile.isEmpty()){
            responseResult = fileUtils.uploadGoods(multipartFile,goods.getGoodsId());
        }
        if (responseResult != null && responseResult.getCode() == 200){
            Object object = responseResult.getObject();
            String fileName = (String) object;
            if (goodsMappper.updateImg(goods.getGoodsId(),fileName) == 1){
                fileUtils.deleteFile(goods.getGoodsSurfaceimg());
                return ResponseResult.success("修改成功！");
            }else{
                fileUtils.deleteFile(fileName);
                return ResponseResult.error("图片修改失败！");
            }
        }
        return ResponseResult.success("修改成功！");
    }


    @Override
    public ResponseResult selectGoodsById(Integer goodsId, Integer state, HttpServletRequest httpRequest) {
        Goods goods = goodsMappper.selectById(goodsId);
        if (goods == null){
            return ResponseResult.error("商品不存在！");
        }
        Integer integer = goods.getGoodsPriceInt();
        Integer decmal = goods.getGoodsPriceDec();
        StringBuffer stringBuffer = new StringBuffer();
        if (decmal >= 100){
            integer += decmal / 100;
            decmal = decmal % 100;
        }
        stringBuffer.append(integer);
        stringBuffer.append(".");
        stringBuffer.append(decmal);
        if (decmal < 10){
            stringBuffer.append(0);
        }
        goods.setGoodsPrice(stringBuffer.toString());
        String ip = CommonUtil.getIpAddress(httpRequest);
        redisUtil.hincr(RedisKeyUtils.MAP_KEY_GOODS,ip,1);
        return ResponseResult.success(goods);
    }



    @Override
    public ResponseResult selectGoodByPage(Integer pageStart, Integer pageSize,Integer state,String classfy) {
        PageHelper.startPage(pageStart,pageSize);
        List<Goods> list = goodsMappper.selectByPage(state,classfy);
        for (Goods goods : list){
            Integer integer = goods.getGoodsPriceInt();
            Integer decmal = goods.getGoodsPriceDec();
            StringBuffer stringBuffer = new StringBuffer();
            if (decmal >= 100){
                integer += decmal / 100;
                decmal = decmal % 100;
            }
            stringBuffer.append(integer);
            stringBuffer.append(".");
            stringBuffer.append(decmal);
            if (decmal < 10){
                stringBuffer.append(0);
            }
            goods.setGoodsPrice(stringBuffer.toString());
        }
        PageInfo<Goods> pageInfo = new PageInfo<Goods>(list);
        return ResponseResult.success(pageInfo);
    }

    @Override
    public ResponseResult visualGoods(String information, Integer pageStart, Integer pageSize,Integer state) {
        PageHelper.startPage(pageStart,pageSize);
        List<Goods> list = goodsMappper.visualSearch(information,state);
        for (Goods goods : list){
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(goods.getGoodsPriceInt());
            stringBuilder.append(".");
            stringBuilder.append(goods.getGoodsPriceDec());
            goods.setGoodsPrice(stringBuilder.toString());
        }
        if (list.size() != 0){
            boolean result = redisUtil.hasKey(RedisKeyUtils.HOT_WRITE);
            if (!result){
                redisUtil.addZset(RedisKeyUtils.HOT_WRITE,information,1);
            }else{
                redisUtil.addScore(RedisKeyUtils.HOT_WRITE,information,1);
            }
        }
        PageInfo<Goods> goods = new PageInfo<>(list);
        return ResponseResult.success(goods);
    }

    @Override
    public ResponseResult getVisitNumber() {
        Object object = redisUtil.get(RedisKeyUtils.GOODS_VISIT);
        if (object != null){
            List<Integer> list = (List<Integer>) object;
            return ResponseResult.success(list);
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 10; i <= 100; i += 10) {
            Integer temp = goodsMappper.countVisit(0,i);
            if (temp == null ){
                list.add(0);
            }else {
                list.add(temp);
            }
        }
        redisUtil.set(RedisKeyUtils.GOODS_VISIT,list,60 * 60 * 2);
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult getHotSearch() {
        Set<Object> result = redisUtil.rangeZset(RedisKeyUtils.HOT_WRITE,0L,12L);
        return ResponseResult.success(result);
    }
}
